package com.briup.client;

import com.briup.Configuration;
import com.briup.entity.Environment;
import com.briup.support.ConfigurationAware;
import com.briup.support.PropertiesAware;
import com.briup.util.Log;

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Properties;

/**
 * @Classname GatherImpl
 * @Description TODO
 * @Date 2023/11/20 16:34
 * @Created by 崔宗祺
 * @Version v1.0.0
 */
public class GatherImpl implements Gather , PropertiesAware , ConfigurationAware {
    private String fileName;
    private Log log;
    @Override
    public Collection<Environment> gather() throws Exception {
        ArrayList<Environment> list = new ArrayList<>();
        BufferedReader br = new BufferedReader(new FileReader(fileName));
        String line =null;
        while ((line = br.readLine()) != null) {
            String[] date = line.split("[|]");
            switch (Integer.parseInt(date[3])) {
                case 16:
                    float finallyTemperature = (getData(date, 0, 4) * (0.00268127F)) - 46.85F;
                    float finallyHumidity = (getData(date, 4, 8) * 0.00190735F) - 6;
                    list.add(getEnvironment(date, "温度", finallyTemperature));
                    list.add(getEnvironment(date, "湿度", finallyHumidity));
                    break;
                case 256:
                    list.add(getEnvironment(date, "光强", getData(date, 0, 4)));
                    break;
                case 1280:
                    list.add(getEnvironment(date, "二氧化碳", getData(date, 0, 4)));
                    break;
            }
        }
//        list.forEach(System.out::println);
        log.info("采集到的数据条数：" + list.size());
        br.close();
        return list;
    }

    public static Environment getEnvironment(String[] date, String name, float data) {
        Environment environment = new Environment();
        if (!"1".equals(date[7])) {
            throw new RuntimeException("遇到非法数据");
        }
        environment.setName(name);
        environment.setData(data);
        environment.setSrcId(date[0]);
        environment.setDesId(date[1]);
        environment.setDevId(date[2]);
        environment.setCount(Integer.parseInt(date[4]));
        environment.setCmd(date[5]);
        environment.setStatus(Integer.parseInt(date[7]));
        environment.setGatherDate(new Timestamp(Long.parseLong(date[8])));
        return environment;
    }
    public static float getData(String[] data, int a, int b) {
        String str2 = data[6];
        String sun = str2.substring(a, b);
        return (float) Integer.parseInt(sun, 16);
    }

    @Override
    public void init(Properties properties) throws Exception {
        fileName = properties.getProperty("fileName");
    }

    @Override
    public void setConfiguration(Configuration configuration) throws Exception {
        log=configuration.getLogger();
    }
}